package com.ruoyi.operation.monitor.strategy;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.operation.domain.TFileResult;
import com.ruoyi.operation.domain.vo.FileMonitorVo;
import com.ruoyi.operation.monitor.IMonitorStrategy;
import com.ruoyi.operation.monitor.domain.CheckResult;
import com.ruoyi.system.api.RemoteTBsCalendarService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.warm.flow.core.utils.IdUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Author Zzneko
 * @Date 2025/7/22 13:37
 * @Descprition：按照日期匹配上一个工作日
 **/
@Slf4j
@Service("1")
public class MonitorOneStrategy implements IMonitorStrategy {

    private static final Pattern DATE_PATTERN = Pattern.compile("(?<!\\d)\\d{8}(?!\\d)");

    @DubboReference
    private RemoteTBsCalendarService remoteTBsCalendarService;

    @Override
    public List<TFileResult> handleMonitorResult(List<FileMonitorVo> fileMonitorVos) {
        List<TFileResult> todayCheckResult = new ArrayList<>();
        //按照每个组进行分类
        Map<String, List<FileMonitorVo>> collect = fileMonitorVos.stream().collect(Collectors.groupingBy(FileMonitorVo::getGroupId));
        collect.forEach((groupId,values)->{
            TFileResult fileResult = checkSingleFileIsExist(values);
            fileResult.setCreateBy("progress");
            fileResult.setCreateTime(new Date());
            fileResult.setId(IdUtils.nextIdStr());
            fileResult.setTestdate(DateUtils.getNowDate());
            fileResult.setFilegroupid(groupId);
            todayCheckResult.add(fileResult);
        });
        return todayCheckResult;
    }


    /**
     * 路径下对比上一日的文件。
     * @param fileMonitorVos
     * @return
     */
    private TFileResult checkSingleFileIsExist(List<FileMonitorVo> fileMonitorVos){
        TFileResult fileResult = new TFileResult();
        String memo = "";
        List<Boolean> resultList = fileMonitorVos.stream().map(x -> {
            try {
                LocalDate today = LocalDate.now();
                String fullpath = x.getFullpath();
                fullpath = StringUtils.replace(fullpath,"{yyyyMMdd}","{}");
                String todayStr = today.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
                String lastDayStr = remoteTBsCalendarService.getLastWorkDay(todayStr).getNatureday();
                String todayFilePath = StrUtil.format(fullpath, todayStr);
                String lastDayFilePath = StrUtil.format(fullpath, lastDayStr);
                File todayFile = new File(todayFilePath);
                File lastDayFile = new File(lastDayFilePath);
                if (!todayFile.exists()||!lastDayFile.exists()) {
                    fileResult.setResultmemo(memo+x.getFullpath()+"文件不存在"+"\n");
                    return Boolean.FALSE;
                }
                List<String> todayFileList = Arrays.stream(todayFile.listFiles()).map(file -> DATE_PATTERN.matcher(file.getName()).replaceAll("")).collect(Collectors.toList());
                List<String> lastFileList = Arrays.stream(lastDayFile.listFiles()).map(file -> DATE_PATTERN.matcher(file.getName()).replaceAll("")).collect(Collectors.toList());
                if (todayFileList.containsAll(lastFileList)&&lastFileList.containsAll(todayFileList)) {
                    return Boolean.TRUE;
                } else {
                    fileResult.setResultmemo(memo+x.getFullpath()+"比对结果不对"+"\n");
                    return Boolean.FALSE;

                }
            } catch (Exception e) {
                log.error("对比时候发生错误,{}",e.getMessage());
            }
            return Boolean.TRUE;
        }).collect(Collectors.toList());
        if (resultList.contains(Boolean.FALSE)) {
            fileResult.setResultvalue("0");
            return fileResult;
        }else{
            fileResult.setResultvalue("1");
            return fileResult;
        }
    }
}
